import { useState } from 'react';
import { Table, Row, Col, Card, Pagination, Space, Tooltip, Button, Form, InputNumber } from 'antd';
import { useRequest, useLocation, useParams } from 'umi';
import { useToggle, useUpdateEffect } from 'ahooks';
import { PageContainer } from '@ant-design/pro-layout';
import { SearchOutlined } from '@ant-design/icons';
import ColumnBuilder from '../BasicList/builder/ColumnBuilder';
import ActionBuilder from '../BasicList/builder/ActionBuilder';
import SearchBuilder from '../BasicList/builder/SearchBuilder';
import { submitFieldsAdaptor, exportFile } from '../BasicList/helper';
import styles from '../BasicList/index.less';

const Index = () => {
  const [pageQuery, setPageQuery] = useState({
    per_page: 10,
    page: 1,
    queryfields: '',
  });
  const [sortQuery, setSortQuery] = useState({
    sort: [],
    order: [],
  });
  const [searchVisible, searchAction] = useToggle(false);
  const [searchForm] = Form.useForm();
  const location = useLocation();
  const params = useParams();
  const currentid = params['1'];

  const init = useRequest<{
    data: BasicListApi.ListData;
  }>(
    (values: any) => {
      if (values === true) {
        //path: /basic-sqlrpt/rptdemoA/103
        return {
          method: 'Post',
          url: '/api/sql-reports/show-report/',
          params: {
            id: currentid,
          },
          data: {
            status: true,
            per_page: 10,
            page: 1,
            sort: [],
            order: [],
          },
        };
      }

      return {
        method: 'Post',
        url: '/api/sql-reports/show-report/',
        params: {
          id: currentid,
        },
        data: {
          status: true,
          ...pageQuery,
          ...sortQuery,
        },
      };
    },
    {
      formatResult: (result: any) => result?.data,
      onSuccess: (data) => {
        console.log('data', data);
      },
    },
  );

  useUpdateEffect(() => {
    init.run();
  }, [pageQuery, sortQuery]);

  useUpdateEffect(() => {
    searchForm.resetFields();
    setPageQuery({
      page: 1,
      per_page: 10,
      queryfields: '',
    });
    setSortQuery({
      sort: [],
      order: [],
    });
  }, [location.pathname]);

  function actionHandler(action: BasicListApi.Action, record: BasicListApi.Field) {
    switch (action.action) {
      case 'reload':
        init.run();
        break;
      case 'exportXls':
        exportFile(
          action.uri || '',
          {
            export: true,
            ...pageQuery,
            ...sortQuery,
          },
          init?.data?.page?.title + '.xlsx',
          {
            id: currentid,
          }
        );
        break;
      default:
        break;
    }
  }

  const paginationChangeHandler = (page: any, per_page: any) => {
    const tmpPageQuery = { ...pageQuery };
    setPageQuery({
      page: page,
      per_page: per_page,
      queryfields: tmpPageQuery.queryfields,
    });
  };

  const tableChangeHandler = (_: any, __: any, sorter: any) => {
    if (sorter.order === undefined) {
      setSortQuery({
        sort: [],
        order: [],
      });
    } else {
      const orderBy = sorter.order === 'ascend' ? 'asc' : 'desc';
      const tmpsort = [];
      tmpsort.push(sorter.field);
      const tmporderBy = [];
      tmporderBy.push(orderBy);
      setSortQuery({
        sort: tmpsort as any,
        order: tmporderBy as any,
      });
    }
  };

  const onFinish = (value: any) => {
    const tmpPageQuery = { ...pageQuery };
    tmpPageQuery.queryfields = JSON.stringify(submitFieldsAdaptor(value));
    setPageQuery(tmpPageQuery);
  };

  const searchLayout = () => {
    return (
      <div style={{ display: searchVisible ? '' : 'none' }}>
        <Card className={styles.searchForm}>
          <Form onFinish={onFinish} form={searchForm}>
            <Row gutter={24}>
              {SearchBuilder(init.data?.layout.searchColumn)}
            </Row>
            <Row>
              <Col sm={24} className={styles.textAlignRight}>
                <Space>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                  <Button
                    onClick={() => {
                      init.run();
                      searchForm.resetFields();
                    }}
                  >
                    重置
                  </Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </Card>
      </div>
    );
  };

  const beforeTableLayout = () => {
    return (
      <Row>
        <Col xs={24} sm={24} className={styles.tableToolbar}>
          <Space>
            <Tooltip title="查询">
              <Button
                shape="circle"
                icon={<SearchOutlined />}
                onClick={() => {
                  searchAction.toggle();
                }}
                type={searchVisible ? 'primary' : 'default'}
              />
            </Tooltip>
            {ActionBuilder(init?.data?.layout?.tableToolBar, actionHandler)}
          </Space>
        </Col>
      </Row>
    );
  };

  const afterTableLayout = () => {
    return (
      <Row>
        <Col xs={24} sm={24} className={styles.tableToolbar}>
          <Pagination
            total={init?.data?.meta?.total || 0}
            current={init?.data?.meta?.page || 1}
            pageSize={init?.data?.meta?.perPage || 10}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `总共 ${total} 条`}
            onChange={paginationChangeHandler}
            onShowSizeChange={paginationChangeHandler}
          />
        </Col>
      </Row>
    );
  };

  return (
    <PageContainer>
      {searchLayout()}
      <Card>
        {beforeTableLayout()}
        <Table
          rowKey="id"
          dataSource={init?.data?.dataSource}
          columns={ColumnBuilder(
            init?.data?.layout?.tableColumn,
            actionHandler,
            init?.data?.page?.tableName,
            false
          )}
          pagination={false}
          loading={init?.loading}
          onChange={tableChangeHandler}
        />
        {afterTableLayout()}
      </Card>
    </PageContainer>
  );
};

export default Index;
